using System;
using System.Threading;
using Mono.Fuse;
using System.Collections.Generic;


namespace Mehat.San.SanFS
{
	public class FileHandleManager
	{	
		private static long							NextIdentifier = 1;
		private static Dictionary<long, FileHandle>	OpenHandles = new Dictionary<long, FileHandle>();
		private static Mutex						Lock = new Mutex();
		
		public static FileHandle Lookup(long Identifier)
		{
			Lock.WaitOne();
			try
			{
				return OpenHandles[Identifier];
			}
			catch
			{
				throw;
			}
			finally
			{
				Lock.ReleaseMutex();
			}
				
		}
		
		public static FileHandle CreateHandle(IFile File, OpenedPathInfo Info)
		{
			Lock.WaitOne();
			try
			{
				FileHandle	fh = new FileHandle(File, Info, NextIdentifier++);
				OpenHandles.Add(fh.Identifier, fh);
				Info.Handle = new IntPtr(fh.Identifier);
				return fh;
			}
			catch 
			{
				throw;
			}
			finally
			{
				Lock.ReleaseMutex();
			}
		}
		
		public static void DestroyHandle(FileHandle Handle)
		{
			Lock.WaitOne();
			try
			{
				OpenHandles.Remove(Handle.Identifier);
			}
			catch
			{
				throw;
			}
			finally
			{
				Lock.ReleaseMutex();
			}
		}
	}
}
